package org.elfen.common.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

public final class HttpUtil {
	private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

	private HttpUtil() {
	}

	public static final String httpClientPost(String url) {
		String result = "";
		HttpClient client = new HttpClient();
		GetMethod getMethod = new GetMethod(url);
		try {
			client.executeMethod(getMethod);
			result = getMethod.getResponseBodyAsString();
		} catch (Exception e) {
			logger.error("", e);
		} finally {
			getMethod.releaseConnection();
		}
		return result;
	}
	
	public static final String httpClientPostWithJson(String url,Map<String,Object> params) {
		String result = "";
		HttpClient client = new HttpClient();
//		GetMethod getMethod = new GetMethod(url);
		PostMethod postMethod = new PostMethod(url);
		try {
			JSONObject jsonParam = new JSONObject();
			Iterator<Map.Entry<String,Object>> it = params.entrySet().iterator();
			while(it.hasNext()){
				Map.Entry<String,Object> entry = it.next();
				jsonParam.put(entry.getKey(), entry.getValue());
			}
			String transJson = jsonParam.toString();
			RequestEntity requestEntity = new StringRequestEntity(transJson, "application/json", "UTF-8");
			postMethod.setRequestEntity(requestEntity);
			
			client.executeMethod(postMethod);
			result = postMethod.getResponseBodyAsString();
			
			System.err.println("请求响应内容："+result);
		} catch (Exception e) {
			logger.error("", e);
		} finally {
			postMethod.releaseConnection();
		}
		return result;
	}

	public static final String httpClientPost(String url, ArrayList<NameValuePair> list) {
		String result = "";
		HttpClient client = new HttpClient();
		PostMethod postMethod = new PostMethod(url);
		try {
			NameValuePair[] params = new NameValuePair[list.size()];
			for (int i = 0; i < list.size(); i++) {
				params[i] = list.get(i);
			}
			postMethod.addParameters(params);
			client.executeMethod(postMethod);
			result = postMethod.getResponseBodyAsString();
		} catch (Exception e) {
			logger.error("", e);
		} finally {
			postMethod.releaseConnection();
		}
		return result;
	}
}
